package cn.itcast.tags.meta

import cn.itcast.tags.utils.DateUtils

/**
 * HBase 元数据解析存储，具体数据字段格式如下所示：
    *inType=hbase
    *zkHosts=bigdata-cdh01.itcast.cn
    *zkPort=2181
    *依据inType类型解析为HBaseMeta，加载业务数据，核心代码如下：
    *hbaseTable=tbl_tag_users
    *family=detail
    *selectFieldNames=id,gender
    *whereCondition=modified#day#30
 */

case class HBaseMeta(
                      zkHosts: String,
                      zkPort: String,
                      hbaseTable: String,
                      family: String,
                      selectFieldNames: String,
                      filterConditions: String
                    )
object HBaseMeta {
  /**
   * 将Map集合数据解析到HBaseMeta中
   *
   * @param ruleMap map集合
   * @return
   */
  def getHBaseMeta(ruleMap: Map[String, String]): HBaseMeta = {
    //whereCondition=modified#day#30 -> filterConditions=modified[ge]20210905,modified[le]20211005
    //a.从标签规则获取whereCondition值
    val whereCondition: String = ruleMap.getOrElse("whereCondition", null)
    //b.判断where条件是否有值，有值进行动态生成日期范围
    val filterConditions = if (null != whereCondition) {
      //step1.field=modified unit=day amount=30
      val Array(field,unit,amount) = whereCondition.split("#")
      //step2.获取当前日期，昨日日期，N天之前日期
      val now_day: String = DateUtils.getNow()
      val yesterdayDate: String = DateUtils.dateCalculate(now_day, -1)
      //计算N天以前的日期
      val agoDate = unit match {
        case "day" => DateUtils.dateCalculate(now_day,-(1*amount.toInt))
        case "month" => DateUtils.dateCalculate(now_day,-(30*amount.toInt))
        case "year" => DateUtils.dateCalculate(now_day,-(365*amount.toInt))
      }

      //step4.计算出过滤条件的语句
      s"$field[le]$yesterdayDate,$field[ge]$agoDate"

    } else null

    if(null!=filterConditions)println(s">>>>>filterConditions:${filterConditions}>>>>>")
    // TODO: 实际开发中，应该先判断各个字段是否有值，没有值直接给出提示，
    HBaseMeta(
      ruleMap("zkHosts"),
      ruleMap("zkPort"),
      ruleMap("hbaseTable"),
      ruleMap("family"),
      ruleMap("selectFieldNames"),
      filterConditions
    )
  }
}

